package im.vinci.server.common.discuz;

import cn.jiguang.commom.utils.StringUtils;
import com.ucenter.api.util.XMLHelper;
import im.vinci.server.common.exceptions.VinciException;
import im.vinci.server.common.exceptions.error.ErrorCode;
import im.vinci.server.user.domain.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;

/**
 * Created by mingjie on 16/11/24.
 */
@Component
public class UcenterClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(UcenterClient.class);

    @Autowired
    private Client client;

    private String parseUrl(String scriptString) {
        String[] ss = scriptString.split(" ");
        return ss[2].substring(5, ss[2].length() - 1);
    }

    public boolean registerUser(UserInfo userInfo) {
        String userName = userInfo.getNickName();
        String password = userInfo.getPassword();
        String email = "vinci@discuz.vinci";

        LOGGER.info("register user userName: {}, password: {}, email: {}", userName, password, email);

        String $returns = client.uc_user_register(userName, password, email);
        int uid = Integer.parseInt($returns);

        if (uid <= 0) {
            String errorInfo;
            String errorInfoToUser = "";
            switch (uid) {
                case -1:
                    throw new VinciException(ErrorCode.USER_NICKNAME_NOTSTANDARD_ERROR, "用户名不合法", "昵称不符合规则");
                case -2:
                    throw new VinciException(ErrorCode.USER_NICKNAME_SENSITIVE_ERROR, "包含不允许注册的词语", "昵称不能包含敏感词汇");
                case -3:
                    throw new VinciException(ErrorCode.USER_NICKNAME_DUPLICATE_ERROR, "用户名已经存在", "昵称重复");
                case -4:
                    errorInfo = "Email格式有误";
                    break;
                case -5:
                    errorInfo = "Email不允许注册";
                    break;
                case -6:
                    errorInfo = "Email已经被注册";
                    break;
                default:
                    errorInfo = "未定义错误";
            }

            throw new VinciException(ErrorCode.INTERNAL_SERVER_ERROR, errorInfo, errorInfoToUser);
        } else {
            return true;
        }
    }

    public String loginUser(UserInfo userInfo) {
        String userName = userInfo.getNickName();
        String result = client.uc_user_login(userName, userInfo.getPassword());

        LOGGER.info("login user in ucenter, userName: {}, password: {}", userName, userInfo.getPassword());

        LinkedList<String> resultList = XMLHelper.uc_unserialize(result);
        if (!resultList.isEmpty()) {
            int uid = Integer.parseInt(resultList.get(0));

            if (uid > 0) {
                userName = resultList.get(1);
                String password = resultList.get(2);
                String email = resultList.get(3);

                LOGGER.info("login user in ucenter OK, userName: {}, password: {}, email: {}", userName, password, email);

                String syncloginResult = client.uc_user_synlogin(uid);
                if (StringUtils.isEmpty(syncloginResult)) {
                    throw new VinciException(ErrorCode.ARGUMENT_ERROR, "同步登录失败", "");
                }
                String url = parseUrl(syncloginResult);
                LOGGER.info("login discuz OK, script: {}, url: {}", syncloginResult, url);
                return url;
            } else {
                String errorInfo;
                switch (uid) {
                    case -1:
                        errorInfo = "用户不存在, 或者被删除";
                        break;
                    case -2:
                        errorInfo = "密码错误";
                        break;
                    case -3:
                        errorInfo = "安全提问错";
                        break;
                    default:
                        errorInfo = "未定义错误";
                }
                throw new VinciException(ErrorCode.ARGUMENT_ERROR, errorInfo, "");
            }
        } else {
            throw new VinciException(ErrorCode.ARGUMENT_ERROR, "登录论坛失败", "");
        }
    }

    public String logoutUser(UserInfo userInfo) {
        String syncLogoutResult = client.uc_user_synlogout();
        if (StringUtils.isEmpty(syncLogoutResult)) {
            throw new VinciException(ErrorCode.ARGUMENT_ERROR, "同步登出失败", "");
        }
        String url = parseUrl(syncLogoutResult);
        LOGGER.info("logout discuz OK, script: {}, url: {}", syncLogoutResult, url);
        return url;
    }

    public boolean updatePassword(UserInfo oldUserInfo, String newPassword) {
        String userName = oldUserInfo.getNickName();
        String result = client.uc_user_edit(userName, oldUserInfo.getPassword(), newPassword, "", 1, "", "");

        LOGGER.info("updatePassword in ucenter, userName: {}, oldPassword: {}, newPassword: {}", userName, oldUserInfo.getPassword(), newPassword);

        int code = Integer.parseInt(result);
        if (code == 1) {
            return true;
        } else {
            String errorInfo;
            switch (code) {
                case 0:
                    errorInfo = "没有做任何修改";
                    break;
                case -1:
                    errorInfo = "旧密码不正确";
                    break;
                case -4:
                    errorInfo = "Email 格式有误";
                    break;
                case -5:
                    errorInfo = "Email 不允许注册";
                    break;
                case -6:
                    errorInfo = "该 Email 已经被注册";
                    break;
                case -7:
                    errorInfo = "没有做任何修改";
                    break;
                case -8:
                    errorInfo = "该用户受保护无权限更改";
                    break;
                default:
                    errorInfo = "未知错误";
                    break;
            }
            throw new VinciException(ErrorCode.ARGUMENT_ERROR, errorInfo, "");
        }
    }
}
